import dayjs from 'dayjs'
import { round } from 'lodash-es'

/**
 * @typedef {Object} thousandSplitConfigProps
 * @property {boolean} [integerResult] 是否只展示整数部分
 * @property {string} [prefix] 前缀
 */

/**
 * 数字千分位
 * @param {string | number} amount
 * @param {thousandSplitConfigProps} param1
 * @returns
 */
const thousandSplit = (amount, { integerResult = false, prefix = '' } = {}) => {
  if (amount === null || amount === undefined || Number.isNaN(amount)) {
    return '0'
  }
  let value = String(amount)
  if (integerResult) {
    value = value.replace(/[.]\d+$/, '')
  }
  const [value1, value2] = value.toString().split('.')
  let result = value1.replace(/\d{1,3}(?=(\d{3})+([.]\d+)*$)/g, '$&,')

  return `${(prefix && prefix.toString()) || ''}${result}${value2 ? `.${value2}` : ''}`
}

/**
 * @typedef {Object} decimalProps
 * @property {number} [fixed] 固定为指定位数
 * @property {number} [min] 最少多少位
 * @property {number} [max] 最多多少位
 * @property {boolean} [igoreLastZero] 是否忽略尾数0
 */

/**
 * @typedef {Object} formatNumberConfigProps
 * @property {string} [unit] 单位
 * @property {boolean} [format] 是否显示数字千分位
 * @property {decimalProps} [decimal] 小数处理规则
 */

/**
 * 处理数字
 * @param {string | number} num
 * @param {formatNumberConfigProps} param1
 * @returns
 */
const formatNumber = (num, { unit = null, format = false, decimal = {} } = {}) => {
  const { fixed = 0, min = 0, max = 0, igoreLastZero = true } = decimal
  const showUnit = unit ? `${unit}` : ''
  let initNum = Number(num)
  if (Number.isNaN(initNum)) {
    return `${showUnit}${(0).toFixed(fixed || min || 0)}`
  }
  let numStr = `${initNum}`
  if (fixed) {
    numStr = `${round(initNum, fixed).toFixed(fixed)}`
  } else if (max) {
    numStr = `${round(initNum, max).toFixed(max)}`
    if (igoreLastZero) {
      let regRxp = new RegExp(`([.][0-9]{${min || 0},})0+$`)
      numStr = (regRxp.test(numStr) && RegExp.leftContext + RegExp.$1) || numStr
    }
  }
  const sign = Number(numStr) < 0 ? '-' : ''
  const numValue = numStr.replace(/-/, '')
  return `${sign}${showUnit}${format ? thousandSplit(numValue) : numValue}`
}

/**
 * 简化处理金额数字的格式化，保留指定位数的小数
 * @param {string | number} num
 * @returns
 */
export const formatMoneyNum = num => formatNumber(num, { unit: '￥', format: true, decimal: { fixed: 2 } })

/**
 * 转换日期
 * @param {dayjs.ConfigType} text
 * @returns
 */
export const formatDate = text => (text ? dayjs(text).format('YYYY-MM-DD') : undefined)

/**
 * 转换具体时间
 * @param {dayjs.ConfigType} text
 * @returns
 */
export const formatDateTime = text => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : undefined)

/**
 * 数字转成汉字
 * @param {number} num 要转换的数字
 * @return 汉字
 * */
export const toChinesNum = num => {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['', '十', '百', '千', '万']
  num = parseInt(num, 10)
  const getWan = temp => {
    const strArr = temp.toString().split('').reverse()
    let newNum = ''
    const newArr = []
    strArr.forEach((item, index) => {
      newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
    })
    const numArr = []
    newArr.forEach((m, n) => {
      if (m !== '零') numArr.push(n)
    })
    if (newArr.length > 1) {
      newArr.forEach((m, n) => {
        if (newArr[newArr.length - 1] === '零') {
          if (n <= numArr[numArr.length - 1]) {
            newNum += m
          }
        } else {
          newNum += m
        }
      })
    } else {
      newNum = newArr[0]
    }

    return newNum
  }
  const overWan = Math.floor(num / 10000)
  let noWan = num % 10000
  if (noWan.toString().length < 4) {
    noWan = '0' + noWan
  }
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}
